const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const PlatoWelcomeTreeProvider = require('./welcomeTree');
const PlatoCategoryTreeProvider = require('./categoryTree');
const PlatoStructTreeProvider = require('./structTree');
const PlatoGraphEditorProvider = require('./editor');

function activate(context) {
  const welcomeTree = new PlatoWelcomeTreeProvider();
  const categoryTree = new PlatoCategoryTreeProvider(context);
  const structTree = new PlatoStructTreeProvider(context);
  const editor = new PlatoGraphEditorProvider(context, categoryTree);

  context.subscriptions.push(
    vscode.commands.registerCommand('plato.initProj', () => {
      if (!vscode.workspace.workspaceFolders) {
        vscode.window.showErrorMessage('No plato project in empty workspace');
      } else {
        const root = vscode.workspace.workspaceFolders[0].uri.fsPath;
        const jsonPath = path.join(root, 'plato.json');
        if (!fs.existsSync(jsonPath)) {
          try {
            fs.writeFileSync(jsonPath, JSON.stringify({ categories: [], structs: [] }, null, 2));
          } catch (err) {
            vscode.window.showErrorMessage(err);
          }
        }
      }
    })
  );

  vscode.window.registerTreeDataProvider('platoWelcomeTree', welcomeTree);
  vscode.window.registerTreeDataProvider('platoCategoryTree', categoryTree);
  vscode.window.registerTreeDataProvider('platoStructTree', structTree);

  vscode.window.registerCustomEditorProvider('plato.graph', editor);
}

function deactivate() {}

module.exports = {
  activate,
  deactivate,
};
